import { BrowserWindow, shell, screen } from 'electron'
import { is } from '@electron-toolkit/utils'
import { join, } from 'path'
import BaseWindow from './components/BaseWindow'

export default class RightClickMenuWindow extends BaseWindow {
  //创建窗口
  create(): void {
    if (this.frame !== null && !this.frame.isDestroyed()) return
    this.frame = new BrowserWindow({
      width: 150,
      height: 115,
      show: false,
      alwaysOnTop: true, // 窗口置顶 默认值为false
      autoHideMenuBar: true, // 隐藏菜单栏 默认值为false
      hasShadow: false, // 禁止窗口阴影 默认值为true
      skipTaskbar: true, // 隐藏任务栏 默认值为false
      useContentSize: true, // 使用内容大小 默认值为false
      movable: false, // 禁止窗口移动 默认值为true
      resizable: false, // 禁止窗口缩放 默认值为true
      transparent: true, // 窗口透明 默认值为false
      focusable: true,
      webPreferences: {
        preload: join(__dirname, '../preload/index.js'),
        sandbox: false, // 禁用沙箱模式
        zoomFactor: 1.0, // 禁止缩放
      }
    })

    this.frame!.on('blur', () => {
      this.hideRightClickMenu()
    })

    this.frame!.on('show', () => {

    })


    const routerPath = '/rightClickMenu'
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
      this.frame.loadURL(process.env['ELECTRON_RENDERER_URL'] + '/#' + routerPath)
    } else {
      this.frame.loadFile(join(__dirname, '../renderer/index.html'), {
        hash: routerPath
      })
    }

    // 设置窗口打开链接的处理方式
    this.frame.webContents.setWindowOpenHandler((details) => {
      shell.openExternal(details.url)
      return { action: 'deny' }
    })
  }
  onDisplay (x, y) {
    const [winW, winH] = this.frame!.getSize() // 获取窗口的宽度和高度
    // 获取当前鼠标所在屏幕
    const currentDisplay = screen.getDisplayNearestPoint({ x, y })
    const workArea = currentDisplay.workArea

    let isLeftClickMenuShow = false

    // 获取aiIconWindow实例
    const aiIconWindow = this.getWindow('aiIconWindow')
    const pos = aiIconWindow.getBounds()

    if (x + winW + pos.width >  workArea.x + workArea.width) {
      x = x - winW - pos.width
      isLeftClickMenuShow = true
    }
    if (y + winH > workArea.y + workArea.height) y = y - winH

    // this.frame?.setPosition(x, y)
    this.frame!.setBounds({
      x,
      y,
      width: 150,
      height: 115
    })
    this.frame?.show()
    this.frame?.webContents.send('right-click-menu-is-left-show', isLeftClickMenuShow)
  }
  showRightClickMenu () {
    const aiIconWindow = this.getWindow('aiIconWindow')
    const pos = aiIconWindow.getBounds()
    const centerPosition = {
      x: pos.x + pos.width / 2,
      y: pos.y + pos.height / 2
    }
    this.onDisplay(Math.round(centerPosition.x + pos.width / 2), Math.round(centerPosition.y))
  }
  async hideRightClickMenu () {
    this.frame?.hide()
  }
}
